package cn.edu.swu.lms;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class ImageManager {
    private Map<String, String> imageMap = new HashMap<>();
    private Scanner scanner = new Scanner(System.in);

    public ImageManager() {
        // 确保基础目录存在
        FileUtils.ensureDirectoryExists(FileUtils.IMAGE_BASE_PATH);
    }


    //下载图片

    public void downloadImage() {
        System.out.print("请输入图片URL: ");
        String url = scanner.nextLine().trim();

        if (url.isEmpty()) {
            System.out.println("URL不能为空！");
            return;
        }

        try {
            // 从URL中提取文件名
            String fileName = extractFileName(url);
            if (fileName.isEmpty()) {
                fileName = "image_" + System.currentTimeMillis() + ".jpg";
            }

            // 使用新的绝对路径
            String savePath = FileUtils.getImageSavePath(fileName);

            // 检查文件是否已存在
            File file = new File(savePath);
            if (file.exists()) {
                System.out.print("文件已存在，是否覆盖？(y/n): ");
                String choice = scanner.nextLine().trim();
                if (!choice.equalsIgnoreCase("y")) {
                    System.out.println("下载已取消。");
                    return;
                }
            }

            // 下载图片
            FileUtils.saveImage(url, savePath);
            imageMap.put(fileName, savePath);
            FileUtils.appendLog("Downloaded: " + url + " -> " + savePath);
            System.out.println("图片下载成功: " + savePath);

        } catch (Exception e) {
            System.err.println("下载失败: " + e.getMessage());
            FileUtils.appendLog("Failed: " + url + " - " + e.getMessage());
        }
    }

    //查看所有已下载图片

    public void listImages() {
        if (imageMap.isEmpty()) {
            // 尝试从指定目录加载已存在的图片
            loadExistingImages();
        }

        if (imageMap.isEmpty()) {
            System.out.println("暂无已下载的图片。");
            return;
        }

        System.out.println("=== 已下载图片列表 ===");
        System.out.println("存储路径: " + FileUtils.IMAGE_BASE_PATH);
        int index = 1;
        for (Map.Entry<String, String> entry : imageMap.entrySet()) {
            File file = new File(entry.getValue());
            String size = file.exists() ? (file.length() / 1024) + " KB" : "文件不存在";
            System.out.println(index + ". " + entry.getKey() + " -> " + entry.getValue() + " (" + size + ")");
            index++;
        }
    }

    //搜索图片

    public void searchImage() {
        System.out.print("请输入要搜索的图片名称: ");
        String name = scanner.nextLine().trim();

        if (name.isEmpty()) {
            System.out.println("搜索名称不能为空！");
            return;
        }

        if (imageMap.isEmpty()) {
            loadExistingImages();
        }

        boolean found = false;
        System.out.println("=== 搜索结果 ===");
        for (Map.Entry<String, String> entry : imageMap.entrySet()) {
            if (entry.getKey().toLowerCase().contains(name.toLowerCase())) {
                File file = new File(entry.getValue());
                String status = file.exists() ? "存在" : "不存在";
                System.out.println("找到: " + entry.getKey() + " -> " + entry.getValue() + " (" + status + ")");
                found = true;
            }
        }

        if (!found) {
            System.out.println("未找到包含 '" + name + "' 的图片。");
        }
    }


    //从URL中提取文件名

    private String extractFileName(String url) {
        try {
            // 移除URL参数
            String cleanUrl = url.split("\\?")[0];
            String fileName = cleanUrl.substring(cleanUrl.lastIndexOf("/") + 1);

            // 如果文件名不包含扩展名，添加默认扩展名
            if (!fileName.contains(".")) {
                fileName += ".jpg";
            }

            return fileName;
        } catch (Exception e) {
            return "image_" + System.currentTimeMillis() + ".jpg";
        }
    }

    //从指定目录加载已存在的图片

    private void loadExistingImages() {
        File imagesDir = new File(FileUtils.IMAGE_BASE_PATH);
        if (imagesDir.exists() && imagesDir.isDirectory()) {
            File[] imageFiles = imagesDir.listFiles((dir, name) ->
                    name.toLowerCase().matches(".*\\.(jpg|jpeg|png|gif|bmp)$"));

            if (imageFiles != null) {
                for (File file : imageFiles) {
                    imageMap.put(file.getName(), file.getAbsolutePath());
                }
                System.out.println("从目录加载了 " + imageFiles.length + " 张现有图片。");
            }
        } else {
            System.out.println("图片目录不存在: " + FileUtils.IMAGE_BASE_PATH);
        }
    }


    //获取图片存储的基础路径

    public String getImageBasePath() {
        return FileUtils.IMAGE_BASE_PATH;
    }
}